package com.member.mp.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.member.common.core.domain.R;
import com.member.mp.web.user.SupperController;
import com.member.shop.domain.*;
import com.member.shop.dto.SecKillType;
import com.member.shop.dto.SeckillData;
import com.member.shop.service.*;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description 【秒杀页】控制器
 * @ClassName SeckillController
 * @Date 2025/4/14 
 * @author luo.yun
 */
@Slf4j
@Api(value = "秒杀页接口", tags = {"秒杀页接口"})
@RestController
@RequestMapping("/wx/kill")
public class SeckillController extends SupperController {

    @Resource
    private ISysBizSeckillPageService sysBizSeckillPageService;
    @Resource
    private ISysBizSeckillGoodsPageService sysBizSeckillGoodsPageService;
    @Resource
    private ISysBizGoodsSkuService sysBizGoodsSkuService;
    @Resource
    private ISysBizGoodsService sysBizGoodsService;
    @Resource
    private ISysBizUserService sysBizUserService;

    /**
     * 首页秒杀页首页数据
     */
    @GetMapping("/queryKillInfo")
    public R<SeckillData> queryKillInfo() {
        Long tenantId = getTenantId();
        Long userId = getUserId();
        List<SysBizSeckillPage> killPages = sysBizSeckillPageService.list(new LambdaQueryWrapper<SysBizSeckillPage>()
                .eq(SysBizSeckillPage::getTenantId,tenantId)
                .eq(SysBizSeckillPage::getDisplayed,0));

        SysBizUser bizUser = sysBizUserService.getById(userId);

        SeckillData data = new SeckillData();
        if(!CollectionUtils.isEmpty(killPages)){

            SysBizSeckillPage seckillPage = killPages.get(0);

            Long memberGradeId = bizUser.getMemberGradeId();
            if(seckillPage.getVisibleUser().contains(memberGradeId.toString())){
                BeanUtils.copyProperties(seckillPage, data);
                // 查询对应的商品信息
                SysBizSeckillGoodsPage goodsPage = sysBizSeckillGoodsPageService.getOne(new LambdaQueryWrapper<SysBizSeckillGoodsPage>()
                        .eq(SysBizSeckillGoodsPage::getSeckillId, seckillPage.getId())
                        .eq(SysBizSeckillGoodsPage::getIsTop, 0)
                        .eq(SysBizSeckillGoodsPage::getTenantId,tenantId));

                List<String> goodsIds = new ArrayList<String>();
                if(goodsPage != null){
                    goodsIds = Arrays.stream(goodsPage.getGoodsId().split(","))
                            .map(String::trim)
                            .filter(s -> !s.isEmpty())
                            .collect(Collectors.toList());
                    List<SysBizGoodsSku> skuList = sysBizGoodsSkuService.selectSysBizGoodsSkuList(new LambdaQueryWrapper<SysBizGoodsSku>()
                            .in(SysBizGoodsSku::getId, goodsIds)
                            .last("ORDER BY FIELD(id," + goodsPage.getGoodsId() + ")")
                    );

                    if(!CollectionUtils.isEmpty(skuList)){
                        skuList.forEach(k->{
                            SysBizGoods bizGoods = sysBizGoodsService.getById(k.getGoodsId());
                            if(bizGoods != null){
                                k.setStock(bizGoods.getStock());
                                k.setFrozenStockCount(bizGoods.getFrozenStockCount());
                                k.setSales(bizGoods.getSales());
                            }
                        });
                    }
                    data.setTopGoodsList(skuList);
                }

                List<String> goodsIds2= new ArrayList<>();
                if(!CollectionUtils.isEmpty(data.getTopGoodsList())){
                    goodsIds2.addAll(goodsIds);
                }
                //如果不够10条 那么从分类里面取剩余的条数
                if(CollectionUtils.isEmpty(data.getTopGoodsList()) || data.getTopGoodsList().size() < 10){
                    List<SysBizSeckillGoodsPage> pageList = sysBizSeckillGoodsPageService.selectSysBizSeckillGoodsPageList(new LambdaQueryWrapper<SysBizSeckillGoodsPage>()
                            .eq(SysBizSeckillGoodsPage::getSeckillId, seckillPage.getId())
                            .eq(SysBizSeckillGoodsPage::getIsTop, 1)
                            .eq(SysBizSeckillGoodsPage::getTenantId,tenantId)
                    );

                    if (!CollectionUtils.isEmpty(pageList)) {
                        for (SysBizSeckillGoodsPage p : pageList) {
                            List<String> goodsIdsList = Arrays.stream(p.getGoodsId().split(","))
                                    .map(String::trim)
                                    .filter(s -> !s.isEmpty())
                                    .collect(Collectors.toList());
                            goodsIds2.addAll(goodsIdsList);
                        }

                        List<String> collect = goodsIds2.stream().distinct().collect(Collectors.toList());
                        collect = collect.stream()
                                .limit(10)
                                .collect(Collectors.toList());
                        String collect1 = collect.stream().collect(Collectors.joining(","));
                        List<SysBizGoodsSku> skuList = sysBizGoodsSkuService.selectSysBizGoodsSkuList(new LambdaQueryWrapper<SysBizGoodsSku>()
                                .in(SysBizGoodsSku::getId, collect)
                                .last("ORDER BY FIELD(id," + collect1 + ")")
                        );
                        if(!CollectionUtils.isEmpty(skuList)){
                            skuList.forEach(k->{
                                SysBizGoods bizGoods = sysBizGoodsService.getById(k.getGoodsId());
                                if(bizGoods != null){
                                    k.setStock(bizGoods.getStock());
                                    k.setFrozenStockCount(bizGoods.getFrozenStockCount());
                                    k.setSales(bizGoods.getSales());
                                    k.setUnit(k.getLongUnit()); // 设置单位为长单位 避免前端发版本 后端暂时只能这么写
                                }
                            });
                        }

                        data.setIndexGoodsList(skuList);
                    }
                }else{
                    data.setIndexGoodsList(data.getTopGoodsList());
                }
            }
        }
        return R.ok(data);
    }

    /**
     * 首页秒杀页分类数据
     */
    @GetMapping("/queryKillCategorize")
    public R<List<SecKillType>> queryKillCategorize() {
        Long tenantId = getTenantId();
        List<SysBizSeckillPage> killPages = sysBizSeckillPageService.list(new LambdaQueryWrapper<SysBizSeckillPage>()
                .eq(SysBizSeckillPage::getTenantId,tenantId)
                .eq(SysBizSeckillPage::getDisplayed,0));

        List<SecKillType> list = new ArrayList<>();

        if(!CollectionUtils.isEmpty(killPages)){
            SysBizSeckillPage seckillPage = killPages.get(0);
            // 查询对应的商品信息
            List<SysBizSeckillGoodsPage> pageList = sysBizSeckillGoodsPageService.selectSysBizSeckillGoodsPageList(new LambdaQueryWrapper<SysBizSeckillGoodsPage>()
                    .eq(SysBizSeckillGoodsPage::getSeckillId, seckillPage.getId())
                    .eq(SysBizSeckillGoodsPage::getIsTop, 1)
                    .eq(SysBizSeckillGoodsPage::getTenantId, tenantId));

            // 使用LinkedHashMap保持原始顺序，保留首次出现的记录
            List<SysBizSeckillGoodsPage> distinctList = pageList.stream()
                    .collect(Collectors.toMap(
                            SysBizSeckillGoodsPage::getModeleTitle,
                            Function.identity(),
                            (existing, replacement) -> existing,
                            LinkedHashMap::new
                    ))
                    .values()
                    .stream()
                    .collect(Collectors.toList());

            distinctList.forEach(p->{
                SecKillType type = new SecKillType();
                type.setId(p.getId());
                type.setModeleTitle(p.getModeleTitle());
                list.add(type);
            });
        }
        return R.ok(list);
    }

    /**
     * 查询分类下的商品数据
     * @return 数据
     */
    @GetMapping("/queryCategorizeGoods/{id}")
    public R<List<SysBizGoodsSku>> queryCategorizeGoods(@PathVariable("id") Long id) {
        Long tenantId = getTenantId();
        List<SysBizGoodsSku> skuList = new ArrayList<>();
        SysBizSeckillGoodsPage goodsPage = sysBizSeckillGoodsPageService.getOne(new LambdaQueryWrapper<SysBizSeckillGoodsPage>()
                .eq(SysBizSeckillGoodsPage::getId, id)
                .eq(SysBizSeckillGoodsPage::getIsTop, 1)
                .eq(SysBizSeckillGoodsPage::getTenantId, tenantId)
        );

        if(goodsPage != null){
            List<Long> goodsIds = Arrays.stream(goodsPage.getGoodsId().split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
            skuList = sysBizGoodsSkuService.selectSysBizGoodsSkuList(new LambdaQueryWrapper<SysBizGoodsSku>()
                    .in(SysBizGoodsSku::getId, goodsIds)
                    .last("ORDER BY FIELD(id," + goodsPage.getGoodsId() + ")")
            );

            skuList.forEach(k->{
                SysBizGoods bizGoods = sysBizGoodsService.getById(k.getGoodsId());
                if(bizGoods != null){
                    k.setStock(bizGoods.getStock());
                    k.setPropTags(bizGoods.getPropTags());
                }
            });
        }

        return R.ok(skuList);
    }

}
